<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents, VxeTableDataRow } from 'vxe-table'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { reactive } from 'vue'
import { type RequestActIndex, useHouseActStatisticIndex, useExportHouseActStatistics } from '@fl/api/anjutong/coupon-statistics'
import { getProjectPage, getChannels } from '@fl/api/anjutong'
import { formatTime } from '@fl/utils'

// defineOptions({
//     // eslint-disable-next-line vue/component-definition-name-casing
//     name: 'data-analysis-housing-act-detail',
// })

// 带参跳转
const route = useRoute()
const outType = route.query.type as string
const outProjectName = route.query.projectName as string
const outStartDate = route.query.startDate as string
const outEndDate = route.query.endDate as string

const tableRef = ref()
const projectOptions = ref<any>()
const channelOptions = ref<any>()

// 搜索条件、分页参数
const initialState = {
    idCard: '',
    recipientMobile: '',
    projectName: '',
    channelName: '',
    receiveTime: ['', ''],
    startReceiveTime: '',
    endReceiveTime: '',
    writeOffTime: ['', ''],
    startWriteOffTime: '',
    endWriteOffTime: '',
    userName: '',
}
const state = ref<RequestActIndex>(cloneDeep(initialState))
const searchConditions = ref<RequestActIndex>(cloneDeep(initialState))

const tablePage = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const initialPage = toRaw({ ...tablePage.value })


if(outType === 'receive') {
    state.value.receiveTime = [outStartDate + ' 00:00:00', outEndDate + ' 23:59:59']
    searchConditions.value.receiveTime = state.value.receiveTime
} else if(outType === 'writeOff') {
    state.value.writeOffTime = [outStartDate + ' 00:00:00' , outEndDate + ' 23:59:59']
    searchConditions.value.writeOffTime = state.value.writeOffTime
}
state.value.projectName = outProjectName
searchConditions.value.projectName = outProjectName

// 查询列表 coupontype 1优惠券，2折扣券
const params = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    idCard: searchConditions.value.idCard,
    recipientMobile: searchConditions.value.recipientMobile,
    projectName: searchConditions.value.projectName,
    channelName: searchConditions.value.channelName,
    userName: searchConditions.value.userName,
    startReceiveTime: searchConditions.value.receiveTime?.[0] ? formatTime(searchConditions.value?.receiveTime[0], 'yyyy-MM-dd 00:00:00') : null,
    endReceiveTime: searchConditions.value.receiveTime?.[1] ? formatTime(searchConditions.value?.receiveTime[1], 'yyyy-MM-dd 23:59:59') : null,
    startWriteOffTime: searchConditions.value.writeOffTime?.[0] ? formatTime(searchConditions.value?.writeOffTime[0], 'yyyy-MM-dd 00:00:00') : null,
    endWriteOffTime: searchConditions.value.writeOffTime?.[1] ? formatTime(searchConditions.value?.writeOffTime[1], 'yyyy-MM-dd 23:59:59') : null
}))
const { data, isLoading } = useHouseActStatisticIndex(params)

// 导出
const exportParams = computed(() => ({
    pageNum: 1,
    pageSize: 999999,
    idCard: state.value.idCard,
    recipientMobile: state.value.recipientMobile,
    projectName: state.value.projectName,
    channelName: state.value.channelName,
    userName: state.value.userName,
    startReceiveTime: state.value.receiveTime?.[0] ? formatTime(state.value?.receiveTime[0], 'yyyy-MM-dd 00:00:00') : null,
    endReceiveTime: state.value.receiveTime?.[1] ? formatTime(state.value?.receiveTime[1], 'yyyy-MM-dd 23:59:59') : null,
    startWriteOffTime: state.value.writeOffTime?.[0] ? formatTime(state.value?.writeOffTime[0], 'yyyy-MM-dd 00:00:00') : null,
    endWriteOffTime: state.value.writeOffTime?.[1] ? formatTime(state.value?.writeOffTime[1], 'yyyy-MM-dd 23:59:59') : null
}))
const { isPending, mutateAsync } = useExportHouseActStatistics(exportParams)

const records = ref()
watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.records)
        tablePage.value.total = data.value.total!
    }
})

// 搜索
function submit() {
    // state.value = state.value = { ...values }
    searchConditions.value = cloneDeep(state.value)
    tablePage.value.currentPage = 1
}

// 重置
function reset() {
    // state.value = initialState
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    tablePage.value = initialPage
}

// 获取项目分页列表
function getProjectPageList() {
    getProjectPage({
        pageNum: 1,
        pageSize: 9999,
    }).then((res) => {
        // console.log(res)
        projectOptions.value = res.records.reduce((pre, cur) => {
            const obj: any = {}
            obj.label = cur.xmmc
            obj.value = cur.xmmc
            pre.push(obj)
            return pre
        }, [])
        // console.log('projectOptions', projectOptions.value)
    })
}

// 获取渠道列表
function getChannelList() {
    getChannels().then((res) => {
        channelOptions.value = res.reduce((pre, cur) => {
            cur.label = cur.channelName
            cur.value = cur.channelName
            pre.push(cur)
            return pre
        }, [])
        // console.log('channelOptions', channelOptions.value)
    })
}

init()

function init() {
    getProjectPageList()
    getChannelList()
}

// 导出
async function exportData() {
    const res = await mutateAsync()
    if (res) {
        const objectUrl = URL.createObjectURL(res)
        location.href = objectUrl
        URL.revokeObjectURL(objectUrl)
    }
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6
        },
        label: '真实姓名',
        prop: 'userName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6
        },
        label: '身份证号',
        prop: 'idCard',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6
        },
        label: '手机号',
        prop: 'recipientMobile',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6
        },
        fieldProps: {
            filterable: true,
        },
        label: '项目名称',
        options: computed(() => {
            return projectOptions.value
        }),
        prop: 'projectName',
        valueType: 'select',
    },
    {
        fieldProps: {
            'endPlaceholder': '结束时间',
            'startPlaceholder': '开始时间',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD',
        },
        label: '领取时间',
        prop: 'receiveTime',
        valueType: 'date-picker',
    },
    {
        fieldProps: {
            'endPlaceholder': '结束时间',
            'startPlaceholder': '开始时间',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD',
        },
        label: '核销时间',
        prop: 'writeOffTime',
        valueType: 'date-picker',
    },
    {
        colProps: {
            span: 6
        },
        fieldProps: {
            filterable: true,
        },
        label: '渠道来源',
        options: computed(() => {
            return channelOptions.value
        }),
        prop: 'channelName',
        valueType: 'select',
    },
]
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 60 },
        { field: 'userName', title: '用户名称' },
        { field: 'userName', title: '真实姓名' },
        { field: 'idCard', title: '身份证号' },
        { field: 'recipientMobile', title: '手机号' },
        { field: 'couponName', title: '优惠券名称' },
        { field: 'discountAmount', title: '优惠价值' },
        { field: 'projectName', title: '项目名称' },
        { field: 'receiveTime', title: '领取时间' },
        { field: 'writeOffTime', title: '核销时间' },
        { field: 'contractId', title: '房屋合同编号' },
        { field: 'channelName', title: '渠道来源' },
    ],
})
</script>

<template>
    <ElCard class="mb-20" shadow="never">
        <SearchForm v-model="state" :columns="columns" submit-text="搜索" @reset="reset" @submit="submit" />
    </ElCard>

    <ElCard shadow="never">
        <SearchTable ref="tableRef" v-bind="gridOptions" v-model:pager="tablePage" :loading="isLoading" :data="records"
            @page-change="handlePageChange" :height="600">
            <template #toolbar_buttons>
                <ElButton type="primary" @click="exportData" :loading="isPending">
                    导出
                </ElButton>
            </template>
        </SearchTable>
    </ElCard>
</template>
